<template>
    <view class="container">
        <!-- 头部地址选择【配送地址】【自提地址】 -->
        <view class="allAddress" :style="deliveryTypes.length > 1 ? '' : 'padding-top:10rpx;'">
            <!-- 发货方式选择标签 -->
            <view class="nav flex flex-wrap" v-if="shouldShowDeliveryTabs">
                <view
                    class="item font-color"
                    :class="selectedDeliveryType === 1 ? 'on' : 'on2'"
                    @tap="selectDeliveryType(1)"
                    v-if="deliveryTypes.includes(1)"
                />
                <view
                    class="item font-color"
                    :class="selectedDeliveryType === 2 ? 'on' : 'on2'"
                    @tap="selectDeliveryType(2)"
                    v-if="deliveryTypes.includes(2)"
                />
            </view>
            
            <!-- 地址选择区域 -->
            <view
                class="address flex flex-wrap flex-center ss-row-between"
                @tap="chooseAddr"
                v-if="selectedDeliveryType === 1"
                :style="deliveryTypes.length > 1 ? '' : 'border-top-left-radius: 14rpx;border-top-right-radius: 14rpx;'"
            >
                <view class="addressCon" v-if="selectedAddress">
                    <view class="name">
                        {{ selectedAddress.name }}
                        <text class="phone">{{ selectedAddress.mobile }}</text>
                    </view>
                    <view class="flex flex-wrap">
                        <text class="default font-color" v-if="selectedAddress.defaultStatus">[默认]</text>
                        <text class="line2">
                            {{ selectedAddress.areaName }} {{ selectedAddress.detailAddress }}
                        </text>
                    </view>
                </view>
                <view class="addressCon" v-else>
                    <view class="setaddress">设置收货地址</view>
                </view>
                <view class="iconfont">
                    <view class="ss-rest-button">
                        <text class="_icon-forward">›</text>
                    </view>
                </view>
            </view>
            
            <!-- 门店自提地址 -->
            <view class="address flex flex-wrap flex-center ss-row-between" v-if="selectedDeliveryType === 2" @tap="chooseAddr">
                <view class="addressCon" v-if="selectedPickUpStore">
                    <view class="name">
                        {{ selectedPickUpStore.name }}
                        <text class="phone">{{ selectedPickUpStore.phone }}</text>
                    </view>
                    <view class="line1">
                        {{ selectedPickUpStore.areaName }}{{ ', ' + selectedPickUpStore.detailAddress }}
                    </view>
                </view>
                <view class="addressCon" v-else>
                    <view class="setaddress">选择自提门店</view>
                </view>
                <view class="iconfont">
                    <view class="ss-rest-button">
                        <text class="_icon-forward">›</text>
                    </view>
                </view>
            </view>
            <view class="line">
                <image :src="'/static/images/line.png'" />
            </view>
        </view>

        <view class="tui-box">
            <!-- 商品信息 -->
            <view class="order-card-box ss-m-b-14">
                <view class="goods-item" v-for="(item, index) in shopCartList" :key="index">
                    <image :src="item.picUrl" class="goods-img"></image>
                    <view class="goods-info">
                        <view class="goods-name">{{ item.spuName }}</view>
                        <view class="goods-sku">
                            <span v-for="property in item.properties" :key="property.propertyId">
                                {{ property.propertyName }}: {{ property.valueName }}
                            </span>
                        </view>
                    </view>
                    <view class="goods-price">
                        <view class="price">￥{{ fen2yuan(item.price) }}</view>
                        <view class="count">x{{ item.count }}</view>
                    </view>
                </view>
            </view>
            <!-- 价格信息 -->
            <view class="bg-white total-card-box ss-p-20 ss-m-b-14 ss-r-10">
                <view class="total-box-content border-bottom">
                    <view class="order-item ss-flex ss-col-center ss-row-between">
                        <view class="item-title">商品金额</view>
                        <view class="item-value">
                            ￥{{ fen2yuan(priceInfo.totalPrice) }}
                        </view>
                    </view>
                    <!-- 显示折扣优惠 -->
                    <view
                        class="order-item ss-flex ss-col-center ss-row-between"
                        v-if="priceInfo.discountPrice > 0"
                    >
                        <view class="item-title">优惠折扣</view>
                        <view class="item-value text-red">
                            -￥{{ fen2yuan(priceInfo.discountPrice) }}
                        </view>
                    </view>
                    <!-- 显示优惠券优惠 -->
                    <view
                        class="order-item ss-flex ss-col-center ss-row-between"
                        v-if="priceInfo.couponPrice > 0"
                    >
                        <view class="item-title">优惠券</view>
                        <view class="item-value text-red">
                            -￥{{ fen2yuan(priceInfo.couponPrice) }}
                        </view>
                    </view>
                    <!-- 显示优惠明细 -->
                    <view
                        class="promotion-details"
                        v-if="promotions && promotions.length > 0"
                    >
                        <view class="promotion-title">优惠明细</view>
                        <view
                            class="promotion-item"
                            v-for="(promotion, index) in promotions"
                            :key="index"
                        >
                            <view class="promotion-header ss-flex ss-col-center ss-row-between">
                                <view class="promotion-name">
                                    <text class="promotion-tag">{{ promotion.name || '促销活动' }}</text>
                                </view>
                                <view class="promotion-amount text-red" v-if="promotion.discountPrice && promotion.discountPrice > 0">
                                    -￥{{ fen2yuan(promotion.discountPrice) }}
                                </view>
                            </view>
                            <view class="promotion-desc" v-if="promotion.description">
                                {{ promotion.description }}
                            </view>
                        </view>
                    </view>
                    <!-- 显示促销活动总优惠（如果有促销活动但discountPrice为0，可能是优惠在promotions中） -->
                    <view
                        class="order-item ss-flex ss-col-center ss-row-between"
                        v-if="getTotalPromotionDiscount() > 0"
                    >
                        <view class="item-title">促销优惠</view>
                        <view class="item-value text-red">
                            -￥{{ fen2yuan(getTotalPromotionDiscount()) }}
                        </view>
                    </view>
                    <!-- 快递配送时显示运费 -->
                    <view
                        class="order-item ss-flex ss-col-center ss-row-between"
                        v-if="selectedDeliveryType === 1"
                    >
                        <view class="item-title">运费</view>
                        <view class="item-value" v-if="priceInfo.deliveryPrice > 0">
                            +￥{{ fen2yuan(priceInfo.deliveryPrice) }}
                        </view>
                        <view class="item-value" v-else>免运费</view>
                    </view>
                    <!-- 门店自提时显示联系人信息 -->
                    <view
                        class="order-item ss-flex ss-col-center ss-row-between"
                        v-if="selectedDeliveryType === 2"
                    >
                        <view class="item-title">联系人</view>
                        <view class="ss-flex ss-col-center">
                            <input
                                v-model="receiverName"
                                placeholder="请填写您的联系姓名"
                                class="remark-input"
                                maxlength="20"
                            />
                        </view>
                    </view>
                    <view
                        class="order-item ss-flex ss-col-center ss-row-between"
                        v-if="selectedDeliveryType === 2"
                    >
                        <view class="item-title">联系电话</view>
                        <view class="ss-flex ss-col-center">
                            <input
                                v-model="receiverMobile"
                                placeholder="请填写您的联系电话"
                                class="remark-input"
                                maxlength="20"
                            />
                        </view>
                    </view>
                </view>
                <view class="total-box-footer ss-font-28 ss-flex ss-row-right ss-col-center ss-m-r-28">
                    <view class="total-num ss-m-r-20">
                        共{{ shopCartList.reduce((acc, item) => acc + item.count, 0) }}件
                    </view>
                    <view>合计：</view>
                    <view class="total-num text-red"> ￥{{ fen2yuan(priceInfo.payPrice) }}</view>
                </view>
            </view>
        </view>


        <!-- 底部支付区域 -->
        <view class="footer-box border-top ss-flex ss-row-between ss-p-x-20 ss-col-center">
            <view class="total-box-footer ss-flex ss-col-center">
                <view class="total-num ss-font-30 text-red">
                    ￥{{ fen2yuan(priceInfo.payPrice) }}
                </view>
            </view>
            <view class="submit-btn-wrapper">
                <button
                    class="ss-reset-button ui-BG-Main-Gradient ss-r-40 submit-btn ui-Shadow-Main"
                    @tap="btnPay"
                >
                    确认支付
                </button>
            </view>
        </view>
        <!-- <t-pay-way :show="show" @close="popupClose"></t-pay-way> -->
        <!-- <t-pay-way :show="show" :order-info="priceInfo" :balance="userBalance" @close="popupClose"
            @confirm="handleConfirmPayment"> -->
        <!-- <t-pay-way :show="show" :sub-order="subOrderInfo" :order-info="priceInfo" @close="popupClose"
            :balance="userBalance" @confirm="handleConfirmPayment"> -->
        <t-pay-way :show="show" :sub-order="subOrderInfo" :order-info="priceInfo" @close="popupClose"
            :balance="userBalance" @confirm="handleConfirmPayment" @cancel="handleCancelPayment"></t-pay-way>

        </t-pay-way>

        </t-pay-way>
        <t-select-coupons :show="couponShow" @close="couponClose"></t-select-coupons>

    </view>
</template>

<script>
    import tPayWay from "../components/views/t-pay-way/t-pay-way"
    import tSelectCoupons from "../components/views/t-select-coupons/t-select-coupons"
    export default {
        components: {
            tPayWay,
            tSelectCoupons
        },
        data() {
            return {
                subOrderInfo: null,
                orderInfo: null,
                hasCoupon: true,
                insufficient: false,
                show: false,
                couponShow: false,
                userBalance: 0, // 用户钱包余额
                selectedAddress: null, // 接口返回的地址信息
                shopCartList: [], // 接口返回的商品信息
                priceInfo: {
                    totalPrice: 0,
                    discountPrice: 0,
                    deliveryPrice: 0,
                    couponPrice: 0,
                    payPrice: 0
                },
                promotions: [], // 接口返回的促销信息
                queryString: '',
                items: [],
                addressId: null, // 地址ID，初始为 null（参考 yudao-mall-uniapp）
                deliveryTypes: [], // 可用的发货方式数组
                selectedDeliveryType: 1, // 当前选择的发货方式，默认为快递发货
                selectedPickUpStore: null, // 选择的自提门店
                receiverName: '', // 门店自提时的联系人姓名
                receiverMobile: '' // 门店自提时的联系人电话
            }
        },
        onLoad(options) {
            console.log(options);

            if (options.orderData) {
                // 新的订单数据格式，包含deliveryTypes
                const orderData = JSON.parse(options.orderData);
                this.items = orderData.items;
                this.deliveryTypes = orderData.deliveryTypes || [];
                this.selectedDeliveryType = this.deliveryTypes.length > 0 ? this.deliveryTypes[0] : 1; // 默认选择第一个可用的发货方式
                
                // 缓存deliveryTypes，防止页面返回时丢失
                if (this.deliveryTypes.length > 0) {
                    try {
                        uni.setStorageSync('order_delivery_types', this.deliveryTypes);
                    } catch (e) {
                        console.error('缓存deliveryTypes失败:', e);
                    }
                }
                
                var data2 = {
                    items: orderData.items,
                    deliveryType: this.selectedDeliveryType,
                    pointStatus: false,
                }
                for (let i = 0; i < data2.items.length; i++) {
                    data2[encodeURIComponent('items[' + i + '' + '].skuId')] = data2.items[i].skuId + '';
                    data2[encodeURIComponent('items[' + i + '' + '].count')] = data2.items[i].count + '';
                }
                delete data2.items;
                this.queryString = Object.keys(data2)
                    .map((key) => key + '=' + data2[key])
                    .join('&');
                this.loadOrderSettlementData(this.queryString);
            } else if (options.items) {
                // 兼容旧的格式
                this.items = JSON.parse(options.items)
                this.deliveryTypes = [1]; // 默认只有快递发货
                this.selectedDeliveryType = 1;
                
                var data2 = {
                    items: JSON.parse(options.items),
                    deliveryType: 1,
                    pointStatus: false,
                }
                for (let i = 0; i < data2.items.length; i++) {
                    data2[encodeURIComponent('items[' + i + '' + '].skuId')] = data2.items[i].skuId + '';
                    data2[encodeURIComponent('items[' + i + '' + '].count')] = data2.items[i].count + '';
                }
                delete data2.items;
                this.queryString = Object.keys(data2)
                    .map((key) => key + '=' + data2[key])
                    .join('&');
                this.loadOrderSettlementData(this.queryString);
            }

            if (options.id) {
                this.addressId = Number(options.id); // 转换为数字类型
                this.loadAddress(options.id);
            }
            
            // 监听自提门店选择事件
            uni.$on('SELECT_PICK_UP_INFO', this.onSelectPickUpStore);
            
            // 加载用户信息，填充联系人和电话
            this.loadUserInfo();
            // 加载钱包余额
            this.loadWalletBalance();
        },
        
        onShow() {
            // 页面显示时，如果deliveryTypes为空或只有一种方式，尝试从缓存恢复
            if (this.deliveryTypes.length <= 1) {
                try {
                    const cachedDeliveryTypes = uni.getStorageSync('order_delivery_types');
                    if (cachedDeliveryTypes && cachedDeliveryTypes.length > 1) {
                        this.deliveryTypes = cachedDeliveryTypes;
                        console.log('从缓存恢复deliveryTypes:', this.deliveryTypes);
                    }
                } catch (e) {
                    console.error('恢复deliveryTypes失败:', e);
                }
            }
            
            // 检查是否有地址ID变化（从地址选择页面返回时）
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            if (currentPage && currentPage.options && currentPage.options.id) {
                const newAddressId = Number(currentPage.options.id); // 转换为数字类型
                if (newAddressId && newAddressId !== this.addressId) {
                    this.addressId = newAddressId;
                    this.loadAddress(newAddressId);
                }
            }
            
            // 重新加载用户信息，确保信息是最新的
            this.loadUserInfo();
            // 重新加载钱包余额
            this.loadWalletBalance();
        },
        
        onUnload() {
            // 页面卸载时移除事件监听
            uni.$off('SELECT_PICK_UP_INFO', this.onSelectPickUpStore);
        },
        computed: {
            // 判断是否应该显示发货方式标签栏
            shouldShowDeliveryTabs() {
                // 如果支持多种发货方式，显示标签栏
                if (this.deliveryTypes.length > 1) {
                    return true;
                }
                // 如果只有一种发货方式，但之前可能支持多种，也显示标签栏
                // 这样可以保持用户的选择状态
                return this.deliveryTypes.length === 1 && (this.deliveryTypes.includes(1) || this.deliveryTypes.includes(2));
            }
        },
        methods: {
            // 分转元函数，参考 yudao-mall
            fen2yuan(price) {
                return (Number(price) / 100).toFixed(2);
            },
            loadOrderSettlementData(queryString) {
                // 参考 yudao-mall-uniapp 的逻辑：如果有地址ID且是快递配送，添加到查询参数中
                let finalQueryString = queryString;
                if (this.addressId && this.selectedDeliveryType === 1 && this.addressId > 0) {
                    // 快递配送时需要地址ID来计算运费
                    if (!finalQueryString.includes('addressId=')) {
                        finalQueryString += `&addressId=${this.addressId}`;
                    }
                }
                
                this.$api.req(`/trade/order/settlement?${finalQueryString}`,{},"GET","JSON",false).then((res) => {
                    if (res.code === 0) {
                        const data = res.data;
                        this.shopCartList = data.items;
                        
                        // 处理地址信息：如果后端返回了地址，更新地址ID（参考 yudao-mall-uniapp 的逻辑）
                        if (data.address && data.address.id) {
                            const newAddressId = Number(data.address.id); // 确保是数字类型
                            const oldAddressId = this.addressId;
                            
                            this.selectedAddress = data.address;
                            this.addressId = newAddressId;
                            
                            // 如果之前没有地址ID（首次加载），且是快递配送，需要重新调用接口计算运费
                            if ((!oldAddressId || oldAddressId <= 0) && this.selectedDeliveryType === 1 && !queryString.includes('addressId=')) {
                                // 重新计算运费（带上地址ID）
                                this.recalculateOrder();
                                return; // 提前返回，等待重新计算的结果
                            }
                        }
                        
                        this.priceInfo = {
                            totalPrice: Number(data.price.totalPrice || 0),
                            discountPrice: Number(data.price.discountPrice || 0),
                            deliveryPrice: Number(data.price.deliveryPrice || 0),
                            couponPrice: Number(data.price.couponPrice || 0),
                            payPrice: Number(data.price.payPrice || 0)
                        };
                        this.promotions = data.promotions || [];
                        
                        // 调试信息：打印价格信息，帮助排查问题
                        console.log('订单结算价格信息:', {
                            totalPrice: this.priceInfo.totalPrice,
                            discountPrice: this.priceInfo.discountPrice,
                            couponPrice: this.priceInfo.couponPrice,
                            deliveryPrice: this.priceInfo.deliveryPrice,
                            payPrice: this.priceInfo.payPrice,
                            promotions: this.promotions,
                            promotionDiscount: this.getTotalPromotionDiscount(),
                            calculatedTotal: this.priceInfo.totalPrice - this.priceInfo.discountPrice - this.priceInfo.couponPrice - this.getTotalPromotionDiscount() + this.priceInfo.deliveryPrice
                        });
                    } else {
                        uni.showToast({
                            title: res.msg || "加载失败",
                            icon: "none",
                        });
                    }
                });
            },
            loadAddress(id) {
                this.$api.req(`/member/address/get?id=${id}`,{},"GET","JSON",false).then((res) => {
                    if (res.code === 0 && res.data) {
                        this.selectedAddress = res.data;
                        this.addressId = Number(res.data.id); // 确保是数字类型
                        // 加载地址后，如果是快递配送，重新计算运费（参考 yudao-mall-uniapp 的逻辑）
                        if (this.selectedDeliveryType === 1) {
                            this.recalculateOrder();
                        }
                    } else {
                        uni.showToast({
                            title: res.msg || "加载地址失败",
                            icon: "none",
                        });
                    }
                });
            },
            chooseAddr() {
                if (this.selectedDeliveryType === 1) {
                    // 快递配送，选择收货地址
                    uni.navigateTo({
                        url: `../address/address?items=${JSON.stringify(this.items)}`
                    })
                } else if (this.selectedDeliveryType === 2) {
                    // 门店自提，选择自提门店
                    uni.navigateTo({
                        url: `../goods_details_store/index?items=${JSON.stringify(this.items)}`
                    })
                }
            },
            btnPay() {
                var t = this
                
                // 验证必填信息
                if (this.selectedDeliveryType === 1 && !this.selectedAddress) {
                    uni.showToast({
                        title: '请选择收货地址',
                        icon: 'none'
                    });
                    return;
                }
                if (this.selectedDeliveryType === 2) {
                    if (!this.selectedPickUpStore) {
                        uni.showToast({
                            title: '请选择自提门店',
                            icon: 'none'
                        });
                        return;
                    }
                    if (!this.receiverName || !this.receiverMobile) {
                        uni.showToast({
                            title: '请填写联系人和联系电话',
                            icon: 'none'
                        });
                        return;
                    }
                    // 验证手机号格式
                    if (!/^1[3-9]\d{9}$/.test(this.receiverMobile)) {
                        uni.showToast({
                            title: '请填写正确的手机号',
                            icon: 'none'
                        });
                        return;
                    }
                }
                
                const orderData = {
                    items: this.items.map(item => {
                        const itemData = {
                            skuId: item.skuId,
                            count: item.count,
                        };
                        // 如果有购物车ID，传递给后端，用于订单创建成功后删除购物车商品
                        if (item.cartId) {
                            itemData.cartId = item.cartId;
                        }
                        return itemData;
                    }),
                    deliveryType: this.selectedDeliveryType,
                    pointStatus: false
                };
                
                // 根据发货方式添加不同的参数
                if (this.selectedDeliveryType === 1) {
                    // 快递配送
                    orderData.addressId = this.selectedAddress.id;
                    orderData.receiverName = this.selectedAddress.name;
                    orderData.receiverMobile = this.selectedAddress.mobile;
                } else if (this.selectedDeliveryType === 2) {
                    // 门店自提
                    orderData.pickUpStoreId = this.selectedPickUpStore.id;
                    orderData.receiverName = this.receiverName;
                    orderData.receiverMobile = this.receiverMobile;
                }

                this.$api.req('/trade/order/create',orderData,'POST','JSON',false).then((res) => {
                    if (res.code === 0) {
                        t.subOrderInfo = res.data
                        // t.priceInfo.payPrice = res.data.payPrice; // 更新支付金额
                        t.show = true; // 显示支付弹窗
                    } else {
                        uni.showToast({
                            title: res.msg || '创建订单失败',
                            icon: 'none'
                        });
                    }
                });
            },
            popupClose() {
                this.show = false;
            },
            handleConfirmPayment({ payMethod }) {
                console.log(`用户选择了支付方式：${payMethod}`);
                this.show = false; // 关闭支付弹窗
                
                // 支付成功后跳转到支付结果页面（钱包支付和微信支付都跳转到同一个页面）
                if (payMethod === 'wechat' || payMethod === 'wallet') {
                    // 显示支付成功提示
                    uni.showModal({
                        title: '支付成功',
                        content: '订单支付成功！',
                        showCancel: false,
                        success: () => {
                            // 跳转到支付成功页面
                            uni.redirectTo({
                                url: `/subPackage2/success/success?orderId=${this.subOrderInfo.id}&payPrice=${this.subOrderInfo.payPrice}`
                            });
                        }
                    });
                }
            },
            // 处理支付取消
            handleCancelPayment({ orderId }) {
                console.log('用户取消了支付，订单ID:', orderId);
                this.show = false; // 关闭支付弹窗
                
                // 跳转到订单详情页面（订单已经是待支付状态）
                if (orderId) {
                    uni.redirectTo({
                        url: `/subPackage2/orderDetail/orderDetail?id=${orderId}`
                    });
                } else {
                    // 如果没有订单ID，返回上一页
                    uni.navigateBack();
                }
            },
            couponClose() {
                this.couponShow = false
            },
            invoice() {
                this.f.nav('../invoice/invoice')
            },
            // 获取发货方式名称
            getDeliveryTypeName(type) {
                const typeMap = {
                    1: '快递发货',
                    2: '门店自提'
                };
                return typeMap[type] || '未知';
            },
            // 选择发货方式（参考 yudao-mall-uniapp 的逻辑）
            selectDeliveryType(type) {
                if (this.selectedDeliveryType !== type) {
                    this.selectedDeliveryType = type;
                    // 重新计算订单价格（地址变化或配送方式变化时都会重新计算）
                    this.recalculateOrder();
                }
            },
            // 重新计算订单价格（参考 yudao-mall-uniapp 的逻辑）
            recalculateOrder() {
                var data2 = {
                    items: this.items,
                    deliveryType: this.selectedDeliveryType,
                    pointStatus: false,
                }
                // 如果有地址ID且是快递配送，添加到参数中（参考 yudao-mall-uniapp 的逻辑）
                if (this.addressId && this.selectedDeliveryType === 1 && this.addressId > 0) {
                    data2.addressId = this.addressId;
                }
                // 如果有自提门店ID，添加到参数中
                if (this.selectedPickUpStore && this.selectedPickUpStore.id && this.selectedDeliveryType === 2) {
                    data2.pickUpStoreId = this.selectedPickUpStore.id;
                }
                
                for (let i = 0; i < data2.items.length; i++) {
                    data2[encodeURIComponent('items[' + i + '' + '].skuId')] = data2.items[i].skuId + '';
                    data2[encodeURIComponent('items[' + i + '' + '].count')] = data2.items[i].count + '';
                }
                delete data2.items;
                // 如果 addressId 为 0 或空，不添加到查询参数中（参考 yudao-mall-uniapp 的 API 逻辑）
                if (data2.addressId && !(data2.addressId > 0)) {
                    delete data2.addressId;
                }
                if (data2.pickUpStoreId && !(data2.pickUpStoreId > 0)) {
                    delete data2.pickUpStoreId;
                }
                
                this.queryString = Object.keys(data2)
                    .map((key) => key + '=' + data2[key])
                    .join('&');
                this.loadOrderSettlementData(this.queryString);
            },
            // 选择自提门店回调
            onSelectPickUpStore(data) {
                if (data && data.addressInfo) {
                    this.selectedPickUpStore = data.addressInfo;
                    console.log('选择的自提门店:', this.selectedPickUpStore);
                }
            },
            
            // 加载用户信息
            async loadUserInfo() {
                try {
                    // 先从本地存储获取用户信息
                    let userInfo = null;
                    try {
                        userInfo = uni.getStorageSync('userInfo');
                    } catch (e) {
                        console.log('本地存储中没有用户信息');
                    }
                    
                    // 如果本地存储没有用户信息，从服务器获取
                    if (!userInfo || !userInfo.nickname || !userInfo.mobile) {
                        const res = await this.$api.req('/member/user/get', {}, 'GET', 'JSON', false);
                        if (res.code === 0 && res.data) {
                            userInfo = res.data;
                            // 更新本地存储
                            try {
                                uni.setStorageSync('userInfo', userInfo);
                            } catch (e) {
                                console.error('更新本地存储失败:', e);
                            }
                        }
                    }
                    
                    // 填充联系人和电话信息
                    if (userInfo) {
                        this.receiverName = userInfo.nickname || '';
                        this.receiverMobile = userInfo.mobile || '';
                        console.log('用户信息加载成功:', {
                            nickname: this.receiverName,
                            mobile: this.receiverMobile
                        });
                    }
                } catch (error) {
                    console.error('加载用户信息失败:', error);
                    // 如果获取失败，尝试从其他存储位置获取
                    try {
                        const user = uni.getStorageSync('cleanbio_user');
                        if (user && user.nickname) {
                            this.receiverName = user.nickname || '';
                            this.receiverMobile = user.mobile || '';
                        }
                    } catch (e) {
                        console.error('从备用存储获取用户信息失败:', e);
                    }
                }
            },
            // 加载钱包余额
            async loadWalletBalance() {
                try {
                    const res = await this.$api.req("/pay/wallet/get", {}, "get", "JSON", false);
                    if (res.code === 0 && res.data) {
                        // 余额是以"分"为单位存储的，直接使用
                        this.userBalance = res.data.balance || 0;
                        console.log('钱包余额加载成功:', this.userBalance);
                    }
                } catch (error) {
                    console.error('获取钱包余额失败', error);
                }
            },
            // 计算促销活动总优惠金额
            getTotalPromotionDiscount() {
                if (!this.promotions || this.promotions.length === 0) {
                    return 0;
                }
                return this.promotions.reduce((total, promotion) => {
                    return total + (Number(promotion.discountPrice) || 0);
                }, 0);
            }
        }
    }
</script>

<style>
    .container {
        padding-bottom: 100rpx;
        background-color: #f5f5f5;
    }

    /* 地址选择区域样式 */
    .allAddress .font-color {
        color: #e93323 !important;
    }
    .line2 {
        width: 504rpx;
    }
    .textR {
        text-align: right;
    }

    .line {
        width: 100%;
        height: 3rpx;
    }

    .line image {
        width: 100%;
        height: 100%;
        display: block;
    }

    .address {
        padding: 28rpx;
        background-color: #fff;
        box-sizing: border-box;
    }

    .address .addressCon {
        width: 596rpx;
        font-size: 26rpx;
        color: #666;
    }

    .address .addressCon .name {
        font-size: 30rpx;
        color: #282828;
        font-weight: bold;
        margin-bottom: 10rpx;
    }

    .address .addressCon .name .phone {
        margin-left: 50rpx;
    }

    .address .addressCon .default {
        margin-right: 12rpx;
    }

    .address .addressCon .setaddress {
        color: #333;
        font-size: 28rpx;
    }

    .address .iconfont {
        font-size: 35rpx;
        color: #707070;
    }

    .address .ss-rest-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40rpx;
        height: 40rpx;
    }

    .address ._icon-forward {
        font-size: 32rpx;
        color: #999;
        font-weight: bold;
    }

    .allAddress {
        width: 100%;
        background: linear-gradient(to bottom, #e93323 0%, #f5f5f5 100%);
        padding-top: 100rpx;
        padding-bottom: 10rpx;
    }

    .allAddress .nav {
        width: 690rpx;
        margin: 0 auto;
    }

    .allAddress .nav .item {
        width: 334rpx;
    }

    .allAddress .nav .item.on {
        position: relative;
        width: 230rpx;
    }

    .allAddress .nav .item.on::before {
        position: absolute;
        bottom: 0;
        content: '快递配送';
        font-size: 28rpx;
        display: block;
        height: 0;
        width: 336rpx;
        border-width: 0 20rpx 80rpx 0;
        border-style: none solid solid;
        border-color: transparent transparent #fff;
        z-index: 2;
        border-radius: 14rpx 36rpx 0 0;
        text-align: center;
        line-height: 80rpx;
    }

    .allAddress .nav .item:nth-of-type(2).on::before {
        content: '到店自提';
        border-width: 0 0 80rpx 20rpx;
        border-radius: 36rpx 14rpx 0 0;
    }

    .allAddress .nav .item.on2 {
        position: relative;
    }

    .allAddress .nav .item.on2::before {
        position: absolute;
        bottom: 0;
        content: '到店自提';
        font-size: 28rpx;
        display: block;
        height: 0;
        width: 401rpx;
        border-width: 0 0 60rpx 60rpx;
        border-style: none solid solid;
        border-color: transparent transparent #f7c1bd;
        border-radius: 36rpx 14rpx 0 0;
        text-align: center;
        line-height: 60rpx;
    }

    .allAddress .nav .item:nth-of-type(1).on2::before {
        content: '快递配送';
        border-width: 0 60rpx 60rpx 0;
        border-radius: 14rpx 36rpx 0 0;
    }

    .allAddress .address {
        width: 690rpx;
        max-height: 180rpx;
        margin: 0 auto;
    }

    .allAddress .line {
        width: 100%;
        margin: 0 auto;
    }

    /* 商品信息样式 */
    .order-card-box {
        background: #fff;
        border-radius: 20rpx;
        margin: 20rpx;
        padding: 20rpx;
    }

    .goods-item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
    }

    .goods-item:last-child {
        border-bottom: none;
    }

    .goods-img {
        width: 120rpx;
        height: 120rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
    }

    .goods-info {
        flex: 1;
    }

    .goods-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        line-height: 1.4;
    }

    .goods-sku {
        font-size: 24rpx;
        color: #999;
    }

    .goods-price {
        text-align: right;
    }

    .price {
        font-size: 28rpx;
        color: #e93323;
        font-weight: bold;
    }

    .count {
        font-size: 24rpx;
        color: #999;
        margin-top: 5rpx;
    }

    /* 价格信息样式 */
    .total-card-box {
        background: #fff;
        border-radius: 20rpx;
        margin: 20rpx;
    }

    .order-item {
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .item-title {
        font-size: 28rpx;
        font-weight: 400;
        color: #333;
    }

    .item-value {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        text-align: right;
    }

    .text-red {
        color: #e93323;
    }

    /* 优惠明细样式 */
    .promotion-details {
        padding: 20rpx 0;
        border-top: 1rpx solid #f5f5f5;
        border-bottom: 1rpx solid #f5f5f5;
        margin: 20rpx 0;
    }

    .promotion-title {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 20rpx;
    }

    .promotion-item {
        display: flex;
        flex-direction: column;
        padding: 16rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
    }

    .promotion-item:last-child {
        border-bottom: none;
    }

    .promotion-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8rpx;
    }

    .promotion-name {
        display: flex;
        align-items: center;
        flex: 1;
    }

    .promotion-tag {
        display: inline-block;
        padding: 4rpx 16rpx;
        background: #fff5f5;
        color: #e93323;
        font-size: 24rpx;
        border-radius: 8rpx;
        border: 1rpx solid #ffcccc;
    }

    .promotion-desc {
        font-size: 24rpx;
        color: #666;
        line-height: 1.5;
        padding-left: 4rpx;
    }

    .promotion-amount {
        font-size: 26rpx;
        font-weight: 500;
    }

    .total-box-footer {
        height: 90rpx;
    }

    .total-num {
        color: #333333;
        font-family: OPPOSANS;
    }

    .border-bottom {
        border-bottom: 1rpx solid #f5f5f5;
    }

    .remark-input {
        text-align: right;
        font-size: 28rpx;
        color: #333;
        border: none;
        outline: none;
        width: 200rpx;
    }

    /* 底部支付区域 */
    .footer-box {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 100rpx;
        background: #fff;
        border-top: 1rpx solid #f5f5f5;
        z-index: 999;
    }

    .submit-btn-wrapper {
        display: flex;
        align-items: center;
    }

    .submit-btn {
        width: 240rpx;
        height: 70rpx;
        font-size: 28rpx;
        font-weight: 500;
        background: linear-gradient(135deg, #e93323 0%, #ff6b6b 100%);
        color: #fff;
        border: none;
        border-radius: 40rpx;
    }

    /* 工具类 */
    .ss-m-b-14 {
        margin-bottom: 28rpx;
    }

    .ss-p-20 {
        padding: 40rpx;
    }

    .ss-r-10 {
        border-radius: 20rpx;
    }

    .ss-flex {
        display: flex;
    }

    .ss-col-center {
        align-items: center;
    }

    .ss-row-between {
        justify-content: space-between;
    }

    .ss-row-right {
        justify-content: flex-end;
    }

    .ss-p-x-20 {
        padding-left: 40rpx;
        padding-right: 40rpx;
    }

    .ss-m-r-20 {
        margin-right: 40rpx;
    }

    .ss-m-r-24 {
        margin-right: 48rpx;
    }

    .ss-m-r-28 {
        margin-right: 56rpx;
    }

    .ss-font-28 {
        font-size: 28rpx;
    }

    .ss-font-30 {
        font-size: 30rpx;
    }

    .bg-white {
        background-color: #fff;
    }

    .border-top {
        border-top: 1rpx solid #f5f5f5;
    }

    .flex {
        display: flex;
    }

    .flex-wrap {
        flex-wrap: wrap;
    }

    .flex-center {
        align-items: center;
    }
</style>